import { awaitWrap, compress } from '@src/assets/js/tool'
import React, { useEffect, useState } from 'react'
import { getRequest, postRequest } from './ajax'
import { useHistory, useParams } from 'react-router-dom'
import { Skeleton, ErrorBlock, Form, Input, Button, Toast } from 'antd-mobile'
import style from './index.module.less'
import logo from '@imgs/logo.png'
import { useAppDispatch, useAppSelector } from '@src/redux/hook'
import { setAssign } from '@src/redux/reducers/common'
import successIcon from '@imgs/success.png'

async function initData (id, setLoading, setData) {
  setLoading(true)
  const [e, d] = await awaitWrap(getRequest(id))
  setLoading(false)
  if (e === null && d !== null) {
    setData(d)
  }
}

async function submitHandle (data, setOk) {
  Toast.show({ content: '签到中', duration: 0 })
  const [e] = await awaitWrap(postRequest(data))
  if (e === null) {
    Toast.clear()
    setOk(true)
  }
}

function Main () {
  const [formRef] = Form.useForm()
  const h = useHistory()
  const p = useParams()
  const dispatch = useAppDispatch()
  const name = useAppSelector(s => s.common.assignName)
  const mobile = useAppSelector(s => s.common.assignMobile)
  const time = useAppSelector(s => s.basic.sendTime)
  const [smsTime, setSmsTime] = useState(0)
  const [loading, setLoading] = useState(false)
  const [data, setData] = useState(null)
  const [hour, setHour] = useState(0)
  const [minute, setMinute] = useState(0)
  const [second, setSecond] = useState(0)
  const [ok, setOk] = useState(false)
  const [hasTime, setHasTime] = useState(true)
  useEffect(() => {
    if (p.id) {
      initData(p.id, setLoading, setData)
    }
  }, [p])
  useEffect(() => {
    let timer
    function loop (t) {
      const n = Date.now()
      let c = t - n
      setHasTime(c > 0)
      const h = Math.floor(c / 3600000)
      c %= 3600000
      const m = Math.floor(c / 60000)
      c %= 60000
      const s = Math.floor(c / 1000)
      setHour(h)
      setMinute(m)
      setSecond(s)
      if (c <= 0) {
        return undefined
      }
      timer = setTimeout(() => {
        loop(t)
      }, 1000)
    }
    if (data && data.begin_datetime) {
      const e = data.begin_datetime * 1000
      loop(e)
    }
    return () => {
      timer && clearTimeout(timer)
    }
  }, [data])
  useEffect(() => {
    if (formRef) {
      if (name) {
        formRef.setFieldValue('name', name)
      }
      if (mobile) {
        formRef.setFieldValue('mobile', mobile)
      }
    }
  }, [name, mobile, formRef])
  useEffect(() => {
    let timer
    function loop (t) {
      const c = Math.floor((Date.now() - t) / 1000)
      if (c < 60) {
        setSmsTime(60 - c)
        timer = setTimeout(() => { loop(t) }, 1000)
      } else {
        setSmsTime(0)
      }
    }
    loop(time);
    () => {
      timer && clearTimeout(timer)
    }
  }, [time])
  if (loading) {
    return (
      <div className={style.loading}>
        <Skeleton.Title animated />
        <Skeleton.Paragraph animated />
      </div>
    )
  }
  if (!data) {
    return (
      <div className={style.empty}>
        <ErrorBlock status='empty' />
      </div>
    )
  }
  if (ok) {
    return (
      <div className={style.success}>
        <div className={style['success-icon']}><img src={successIcon} /></div>
        <div className={style['success-inner']}>
          <div className={style['success-banner']}>
            <img src={logo} className={style.logo} />
            <div className={style['success-info']}>签到成功</div>
          </div>
        </div>
      </div>
    )
  }
  return (
    <div className={style.container}>
      <div className={style.header}>
        <img src={logo} className={style.logo} />
        {
          hasTime && (
            <div className={style.time}>
              <div className={style['time-top']}>距会议开始</div>
              <div className={style['time-bottom']}>
                {
                  (hour !== 0) && (
                    <>
                      <span className={style.num}>{hour}</span>
                      <span>小时</span>
                    </>
                  )
                }
                {
                  (hour !== 0 || minute !== 0) && (
                    <>
                      <span className={style.num}>{minute}</span>
                      <span>分钟</span>
                    </>
                  )
                }
                <span className={style.num}>{second}</span>
                <span>秒</span>
              </div>
            </div>
          )
        }
      </div>
      <div className={style.body}>
        <Form layout='horizontal' form={formRef} onFinish={(d) => {
          d.mobile = compress(d.mobile)
          submitHandle({ ...d, id: p.id }, setOk)
        }}>
          <Form.Item label='姓名' name='name' rules={[{ required: true, message: '姓名不能为空' }]}>
            <Input placeholder='请输入' />
          </Form.Item>
          <Form.Item label='手机号' name='mobile' rules={[{ required: true, message: '手机号不能为空' }]}>
            <Input placeholder='请输入' maxLength={11} type='number' />
          </Form.Item>
          <Form.Item name='verification' label='短信验证码' rules={[{ required: true, message: '短信验证码不能为空' }]} extra={smsTime > 0 ? (
            <Button disabled>{smsTime}秒</Button>
          ) : (
            <Button onClick={() => {
              const o = formRef.getFieldsValue()
              dispatch(setAssign(o))
              h.push(`/sendSms?mobile=${o.mobile}`)
            }}>发送验证码</Button>
          )}>
            <Input placeholder='请输入' />
          </Form.Item>
        </Form>
      </div>
      <div className={style.btn}>
        <Button color='primary' size='large' block onClick={() => {
          formRef.submit()
        }}>签到</Button>
      </div>
    </div>
  )
}

export default Main
